import Vue from 'vue'
import Router from 'vue-router'
// import Index from '@/pages/Index/Index'
// import Login from '@/pages/Login/Login'
// import Detail from '@/pages/Detail/Detail'
// import Edit from '@/pages/Edit/Edit'
// import Create from '@/pages/Create/Create'
// import Register from '@/pages/Register/Register'
// import User from '@/pages/User/User'
// import My from '@/pages/My/My'

import store from '../store'

Vue.use(Router)

// const router = new Router({
//   routes: [
//     {
//       path: '/',
//       component: Index
//     },
//     {
//       path: '/login',
//       component: Login
//     },
//     {
//       path: '/register',
//       component: Register
//     },
//     {
//       path: '/detail/:blogId',
//       component: Detail
//     },
//     {
//       path: '/edit/:blogId',
//       component: Edit,
//       meta: { requiresAuth: true}
//     },
//     {
//       path: '/create',
//       component: Create,
//       meta:{ requiresAuth: true}
//     },
//     {
//       path: '/user/:userId',
//       component: User
//     },
//     {
//       path: '/my',
//       component: My,
//       meta:{ requiresAuth: true}
//     }
//   ]
// })

const router = new Router({
  routes: [
    {
      path: '/',
      component: () => import('@/pages/Index/Index.vue')
    },
    {
      path: '/login',
      component: () => import('@/pages/Login/Login.vue')
    },
    {
      path: '/register',
      component: ()=> import('@/pages/Register/Register.vue')
    },
    {
      path: '/detail/:blogId',
      component: ()=> import('@/pages/Detail/Detail.vue')
    },
    {
      path: '/edit/:blogId',
      component: ()=> import('@/pages/Edit/Edit.vue'),
      meta: { requiresAuth: true}
    },
    {
      path: '/create',
      component: ()=> import('@/pages/Create/Create.vue'),
      meta:{ requiresAuth: true}
    },
    {
      path: '/user/:userId',
      component: ()=> import('@/pages/User/User.vue')
    },
    {
      path: '/my',
      component: ()=> import('@/pages/My/My.vue'),
      meta:{ requiresAuth: true}
    }
  ]
})

router.beforeEach((to,from,next)=>{
  if(to.matched.some(record => record.meta.requiresAuth)){
    store.dispatch('checkLogin').then(isLogin =>{
      if(!isLogin){
        next({
          path:'/login',
          query:{ redirect: to.fullPath}
        })
      } else{
        next()
      }
    })    
  } else{
    next()
  }
})

export default router